package com.maltys.tree;

import com.maltys.tree.base.TreeNode;

import java.util.*;

/**
 *
 * @author malty
 * @link <a href="https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/">寻找众数</a>
 */
public class ModeInBst {
    private Integer pre;
    private List<Integer> mode = new ArrayList<>();
    private int cnt = 0;
    private int maxCnt = 0;

    public int[] findMode(TreeNode root) {
        traverse(root);
        int[] res = new int[mode.size()];
        for (int i = 0; i < mode.size(); i++) {
            res[i] = mode.get(i);
        }
        return res;
    }


    private void traverse(TreeNode root) {
        if (root == null) {
            return;
        }
        if (pre == null) {
            pre = root.val;
        }

        if (root.left != null) {
            traverse(root.left);
        }

        if (root.val == pre) {
            cnt++;
        } else {
            pre = root.val;
            cnt = 1;
        }
        if (cnt > maxCnt) {
            mode.clear();
            mode.add(pre);
            maxCnt = cnt;
        } else if (cnt == maxCnt) {
            mode.add(pre);
        }

        if (root.right != null) {
            traverse(root.right);
        }
    }

    public static void main(String[] args) {
        ModeInBst modeInBst = new ModeInBst();
        TreeNode root = new TreeNode(1);
        TreeNode right = new TreeNode(2);
        root.right = right;
//        TreeNode rightLeft = new TreeNode(2);
//        right.left = rightLeft;
        int[] modeInBstMode = modeInBst.findMode(root);
        System.out.println(Arrays.toString(modeInBstMode));
    }
}
